from market.models import Asset, Player, Strategy, Fund
from market.models import History
from market.models import AssetForHistory
from market.models import StrategyForHistory
from market.models import PlayerPortfolioForHistory
from market.view import View

from market.chat.betroomBot import sendOnBetroomChat

from market.strategyAndFundHelper import getFundMtM, getPortfolioMtM


# create a new history
# we pass the strategy list which performance is 0 accross the transaction
def createHistory( marketData, zeroPerfStratList, player, actionTaken ):
    betroom = marketData.getBetroom()
    hl = [ hh for hh in History.objects.filter(betroom=betroom)]
    if len( hl )  > 0 :
            previousHisto = hl[len( hl ) - 1]

    h = History(betroom = player.mainStrategy.betroom, bettingPlayerName=player.userBeingThisPlayer.username, actionTaken=actionTaken)
    h.save()

    #ASSETS
    for a in Asset.objects.filter(isAvailableForStandardStrategy=True, betroom = player.mainStrategy.betroom ):
        afh = AssetForHistory(
            asset = a,
            history = h,
            price = marketData.getAssetPrice( a )
            )
        afh.save()


    #STRATEGIES
    for s in Strategy.objects.filter( betroom = betroom ):
        mtm = marketData.getStrategyMtM( s )
        np = 0
        na = 0
        for p in Player.objects.filter(mainStrategy__betroom = betroom):
            for f in Fund.objects.filter( player = p ):
                if f.strategy == s:
                    np = np + 1
                    na = na + f.numberOfAssetsInFund
        # IMPLEMENT strategyPerfSinceLastHistoryDate:
        # If there is no previous history: 0
        # If there is a previous history date
        #   in case it is not the changing strategy: mtm before / mtm - 1
        #   in case of the changing strategy: 0
        perf = 0
        
        if len( hl )  > 0 and zeroPerfStratList.count(s) == 0:#there is a prvious history and the strategy is not forced to have a zero perf
            # get the same strat at last history date
            ss = previousHisto.strategyforhistory_set.filter(strategy=s)
            if len(ss)==1:# we get the strategy at the previous history date.
                if( ss[0].strategyMtM != 0 ):
                    perf = mtm / ss[0].strategyMtM - 1

        sfh = StrategyForHistory(
            strategy = s,
            history = h,
            strategyMtM = mtm,
            strategyPerfSinceLastHistoryDate = perf,
            numberOfPlayersInvestedInTheStrategy = np,
            totalNumberOfAssetInvestedInTheStrategy = na )
        sfh.save()

    #PORTFOLIOSS
    for p in Player.objects.filter(mainStrategy__betroom = betroom):
        mtm = getPortfolioMtM( p, marketData )
        if mtm == 0:
            perc = 1
        else:
            perc = getFundMtM( p, marketData,  p.mainStrategy ) / mtm
        pfh = PlayerPortfolioForHistory(
            player = p,
            history = h,
            portfolioMtM = mtm,
            investementInMainStrategyPercentage = perc,
            numberOfStrategies = len(Fund.objects.filter( player = p )) )
        pfh.save()

    # notify the users
    sendOnBetroomChat( betroom, player.userBeingThisPlayer.username, str(h) )    
        
    return
        
